# 封闭图形个数(好题)
from functools import cmp_to_key

from leetcode import test_function as tf


def smaller(x: int, y: int):
    """定义比较大小的方法"""
    mapping = {"1": 0, "0": 1, "2": 0, "3": 0, "4": 1, "5": 0, "6": 1, "7": 0, "8": 2, "9": 1}
    res_x, res_y = 0, 0

    for num in str(x):  # 遍历每一个字符
        res_x += mapping.get(num)
    for num in str(y):
        res_y += mapping.get(num)

    if res_x == res_y:
        return x - y
    else:
        return res_x - res_y


def sort_by_closed_bubble(arr):
    """使用冒泡排序法
    排序默认需要进行n轮, 每一顿都会找到一个最大的元素置于末尾, 并且每一轮末尾的元素不再进入下一轮循环
    """
    n = len(arr)
    for i in range(n):  # 排序默认需要进行n轮,
        swapped = False
        for j in range(0, n - i - 1):  # 每一顿都会找到一个最大的元素置于末尾, 并且每一轮末尾的元素不再进入下一轮循环
            if smaller(arr[j + 1], arr[j]):
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:  # 如果本轮没有交换, 则认为数组已经完全排序, 退出循环
            break
    return " ".join([str(num) for num in arr])


def sort_by_closed_cmp_key(arr):
    arr.sort(key=cmp_to_key(smaller))
    return " ".join([str(num) for num in arr])


def sort_by_closed_tuple(arr):
    """使用元组的默认排序规则: 元组的默认排序的优先级为对比首个位置, 然后依次比较后续位置"""
    mapping = {"0": 1, "1": 0, "2": 0, "3": 0, "4": 1, "5": 0, "6": 1, "7": 0, "8": 2, "9": 1}
    t = []
    for num in arr:
        closed = 0
        for c in str(num):
            closed += mapping[c]
        t.append((closed, num))
    l = sorted(t)
    return " ".join([str(b) for a, b in l])


if __name__ == '__main__':
    with open("../../data/2024_posta_c.in", "r") as file:
        n = int(file.readline())
        arr = list(map(int, file.readline().split()))
    with open("../../data/2024_posta_c.out", "r") as file:
        ans = file.readline()

    inp = [{"arr": [18, 29, 6]},
           {"arr": [11172, 11713, 11773, 1217, 12322, 13, 13251, 13523, 13533, 13535, 13571, 13]},
           {"arr": arr},
           ]
    out = ["6 29 18", "13 13 1217 11172 11713 11773 12322 13251 13523 13533 13535 13571", ans]
    # tf(sort_by_closed_bubble, inp, out)
    tf(sort_by_closed_cmp_key, inp, out)  # 4.593139s
    tf(sort_by_closed_tuple, inp, out)  # 0.220341s
